package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.health.dto.CheckGroupDTO;
import com.itheima.health.dto.SetmealDTO;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.mapper.CheckGroupMapper;
import com.itheima.health.mapper.SetmealMapper;
import com.itheima.health.pojo.CheckGroup;
import com.itheima.health.pojo.CheckItem;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.CheckGroupService;
import com.itheima.health.service.CheckItemService;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.aliyunoss.AliyunUtils;
import com.itheima.health.utils.redis.RedisUtil;
import com.itheima.health.utils.resources.RedisConstant;
import com.itheima.health.vo.CheckGroupVO;
import com.itheima.health.vo.SetmealVO;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service
@Transactional
//@Log4j2
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    final  static Logger logger = LoggerFactory.getLogger(SetmealServiceImpl.class);

    //  add   update
    @Override
    public boolean saveUpdate(SetmealDTO setmealDTO) {
        //   添加 （insert  中间  for  insert）和 编辑 (update  中间表 根据当前检查组id 清空  再 for  insert)
          boolean flag = saveOrUpdate(setmealDTO);
          int sid = setmealDTO.getId();
        //  中间表录入  for
        Integer[] checkgroupIds = setmealDTO.getCheckgroupIds();
        if(checkgroupIds!=null){
             for (Integer gid : checkgroupIds) {
                 baseMapper.addSetmealAndCheckGroupIds(sid,gid);
             }
         }
         if(setmealDTO.getImg()!=null){
            //  集合中移除 该图片
             RedisUtil.removeSetMember(RedisConstant.ALL_SETMEAL_PIC_SET,setmealDTO.getImg());
         }
        return flag;
    }
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page pageData =null;
        //  条件构造器
        QueryWrapper<Setmeal> wrapper = new QueryWrapper<Setmeal>();
        if(StringUtils.isBlank(queryPageBean.getQueryString())){
            //  无条件分页
            //  page  结合 分页插件
            pageData   = page(new Page(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()));
        }else{
            wrapper.like("name",queryPageBean.getQueryString()).or().like("helpcode",queryPageBean.getQueryString());
          //  where  xxx = xxx  or  yyy = xxx
            //            wrapper.and(i->i.like("name",queryPageBean.getQueryString()).or().like("helpcode",queryPageBean.getQueryString()));
            pageData   = page(new Page(queryPageBean.getCurrentPage(), queryPageBean.getPageSize()),wrapper);
        }
        // 2  结果集封装 PageResult返回
        PageResult pageResult = new PageResult(pageData.getTotal(),pageData.getRecords());
        return pageResult;
    }

    @Override
    public void clearOssImg() {
      //  获取redis 所有集合数据   比对 单个redis图片 有无存在  找不到  oss 删除
        Set<String> members = RedisUtil.getMembersOfSet(RedisConstant.ALL_SETMEAL_PIC_SET);
        if(members!=null&&members.size()!=0){
            for (String desImg : members) {
                boolean flag = RedisUtil.existsKey(RedisConstant.SINGLE_PIC + desImg);
                 if(flag==false){
                     AliyunUtils.deleteFile(desImg);  //  oss图片删除
                     RedisUtil.removeSetMember(RedisConstant.ALL_SETMEAL_PIC_SET,desImg);
                     logger.info(desImg+"----oss图片清理了---");
                 }
            }
        }
    }

    @Override
    public SetmealVO findSetMealDetailById(int id) {
        //  1.. 根据套餐id  查询对应套餐基本信息
           SetmealVO setmealVO = baseMapper.findSetmealById(id);

        //  2.   根据套餐id  查询 对应检查组信息   t_setmeal_checkgroup--t_checkgroup---List<CheckGroupVO>
        List<CheckGroupVO> checkGroupVOList =  baseMapper.findCheckGroupListBySetmealId(id);

        //  3.  根据检查组id  查询对应检查项信息  t_checkgroup_checkitem --  t_checkitem  --List<CheckItem>
        for (CheckGroupVO checkGroupVO : checkGroupVOList) {
           List<CheckItem> checkItemList =  baseMapper.findCheckItemByGroupId(checkGroupVO.getId());
           checkGroupVO.setCheckItems(checkItemList);
        }

        setmealVO.setCheckGroupVOList(checkGroupVOList);

        return setmealVO;
    }
//
//    @Override
//    public CheckGroupVO findCheckIteminfosByGroupId(int id) {
//        //  CheckGroupVO(检查组基本信息，对应检查项ids, 所有检查项列表)
//        CheckGroupVO checkGroupVO =  baseMapper.findCheckGroupById(id);
//        checkGroupVO.setCheckItems(checkItemService.list());
//        int[] checkItemIds = baseMapper.findCheckItemIdsByGroupId(id);
//        checkGroupVO.setCheckItemIds(checkItemIds);//  中间表  根据检查组id 查询对应检查项ids
//        return checkGroupVO;
//    }
}
